package controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		if(session.getAttribute("users")!=null)
		{
			try {
				response.sendRedirect("/register");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String[] listError = new String[6];
		request.setAttribute("listError", listError);
		try {
			request.getRequestDispatcher("/register.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String username = request.getParameter("username");
		String password="";
		try {
			password = Utils.md5(request.getParameter("password"));
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		HttpSession session = request.getSession();
		if(session.getAttribute("users")!=null)
		{
			try {
				response.sendRedirect("/create-blog");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		DBCollection collection = Data.data("users");
		DBObject dbObject = collection.findOne(new BasicDBObject("username",username).append("password", password).append("active", "yes"));
		if(dbObject!=null)
		{
			session.setAttribute("users", dbObject);
			response.sendRedirect("/create-blog");
			return;
		} else {
			DBObject dbObject1 = collection.findOne(new BasicDBObject("username",username).append("password", password));
			if(dbObject1==null)
				request.setAttribute("info", "Username or password incorect !");
			else
				request.setAttribute("info", "Please login to the registered email to active your account. !");
		}
		String[] listError = new String[6];
		request.setAttribute("listError", listError);
		request.setAttribute("usernames", username);
		request.setAttribute("login", "login");
		try {
			request.getRequestDispatcher("/register.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
